<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
			<el-form-item label="部门名称" prop="deptName">
				<el-input v-model="queryParams.deptName" placeholder="请输入部门名称"	clearable style="width: 200px" @keyup.enter="handleQuery" />
			</el-form-item>
			<el-form-item label="状态" prop="disable">
				<el-select v-model="queryParams.disable" placeholder="部门状态" clearable style="width: 200px" @change="handleQuery">
					<el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value + ''" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" @click="handleQuery">搜索</el-button>
				<el-button @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" icon="Plus"	@click="handleAdd" v-hasPermi="['system:dept:add']">新增部门</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
			</el-col>
			<right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
		</el-row>

		<el-table
			border
			v-if="refreshTable"
			v-loading="loading"
			:data="deptList"
			row-key="deptId"
			:default-expand-all="isExpandAll"
			:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
		>
				<el-table-column prop="deptName" label="部门名称" show-overflow-tooltip></el-table-column>
				<el-table-column prop="managerName" label="主管人员" show-overflow-tooltip></el-table-column>
				<el-table-column prop="description" label="部门描述" min-width="160" show-overflow-tooltip></el-table-column>
				<el-table-column prop="disable" label="状态" align="center" width="80">
					<template #default="scope">
						<dict-tag :options="sys_normal_disable" :value="scope.row.disable + ''" />
					</template>
				</el-table-column>
				<el-table-column prop="sort" label="排序" align="center" width="80"></el-table-column>
				<el-table-column prop="createTime" label="创建时间" width="160">
					<template #default="scope">
						<span>{{ parseTime(scope.row.createTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width" fixed="right">
					<template #default="scope">
						<el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['system:dept:add']">添加下级</el-button>
						<el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:dept:edit']">编辑</el-button>
						<el-button v-if="scope.row.parentId != '0'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:dept:remove']">删除</el-button>
					</template>
				</el-table-column>
		</el-table>

		<!-- 添加或修改部门对话框 -->
		<el-dialog :title="title" v-model="open" width="500px" append-to-body>
			<el-form ref="deptRef" :model="form" :rules="rules" label-width="auto">
				<el-form-item label="部门名称" prop="deptName">
					<el-input v-model="form.deptName" placeholder="请输入部门名称" />
				</el-form-item>
				<el-form-item label="上级部门" prop="parentId" v-if="form.parentId != '0'">
					<el-tree-select
						v-model="form.parentId"
						:data="deptOptions"
						:props="{ value: 'deptId', label: 'deptName', children: 'children' }"
						value-key="deptId"
						placeholder="请选择上级部门"
						check-strictly
					/>
				</el-form-item>
				<el-form-item label="主管人员" prop="manager">
					<el-select v-model="form.manager" placeholder="请选择">
						<el-option v-for="item in managerOptions" :key="item.userId" :label="item.nickname" :value="item.userId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="状态" prop="disable">
					<el-radio-group v-model="form.disable">
						<el-radio v-for="dict in sys_normal_disable" :key="dict.value" :value="JSON.parse(dict.value)">{{ dict.label }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="排序" prop="sort">
					<el-input-number v-model="form.sort" controls-position="right" :min="0" />
				</el-form-item>
				<el-form-item label="部门描述" prop="description">
					<el-input v-model="form.description" type="textarea" placeholder="请输入部门描述" :rows="3" maxlength="300" show-word-limit></el-input>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button type="primary" @click="submitForm">确 定</el-button>
					<el-button @click="cancel">取 消</el-button>
				</div>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="Dept">
import { listDept, getDept, delDept, addDept, updateDept } from "@/api/system/dept"
import { listUser } from "@/api/system/user"

const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")

const deptList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")
const deptOptions = ref([])
const isExpandAll = ref(true)
const refreshTable = ref(true)
const managerOptions = ref([])

const data = reactive({
  form: {},
  queryParams: {
		size: -1,
    deptName: undefined,
    disable: undefined
  },
  rules: {
		deptName: [{ required: true, message: "部门名称不能为空", trigger: "blur" }],
    parentId: [{ required: true, message: "上级部门不能为空", trigger: ["blur", "change"] }],
		manager: [{ required: true, message: "主管人员不能为空", trigger: ["blur", "change"] }],
    sort: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询部门列表 */
function getList() {
  loading.value = true
  listDept(queryParams.value).then(response => {
		const result = response.result || {}
    deptList.value = proxy.handleTree(result.records, "deptId")
    loading.value = false
  })
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    deptId: undefined,
    deptName: undefined,
		parentId: undefined,
		manager: undefined,
    sort: 0,
    description: undefined,
    disable: false
  }
  proxy.resetForm("deptRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  listDept({ size: -1, disable: false }).then(response => {
		const result = response.result || {}
    deptOptions.value = proxy.handleTree(result.records, "deptId")
  })
	listUser({size: -1}).then(response => {
		const result = response.result || {}
    managerOptions.value = result.records || []
  })
	title.value = "添加部门"
  if (row != undefined) {
    form.value.parentId = row.deptId
		title.value = "添加下级"
  }
  open.value = true
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false
  isExpandAll.value = !isExpandAll.value
  nextTick(() => {
    refreshTable.value = true
  })
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
	listDept({ size: -1, disable: false }).then(response => {
		const result = response.result || {}
		let data = result.records || []
		data = data.filter(item => item.deptId !== row.deptId)
    deptOptions.value = proxy.handleTree(data, "deptId")
  })
	listUser({size: -1}).then(response => {
		const result = response.result || {}
    managerOptions.value = result.records || []
  })
  getDept(row.deptId).then(response => {
    form.value = response.result || {}
    open.value = true 
    title.value = "编辑部门"
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["deptRef"].validate(valid => {
    if (valid) {
      if (form.value.deptId != undefined) {
        updateDept(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addDept(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除部门名称为"' + row.deptName + '"的部门?').then(function() {
    return delDept(row.deptId)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
</script>
